package com.uwlaser.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.domain.ProductCoding;
import com.uwlaser.exception.EntityExistException;
import com.uwlaser.service.ProductCodingService;
import com.uwlaser.service.dto.ProductCodingDto;
import com.uwlaser.service.dto.ProductCodingQueryParam;
import com.uwlaser.service.mapper.ProductCodingMapper;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import com.uwlaser.utils.enums.DictValueEnum;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* @author zk-Qin
* @date 2022-05-11
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = ProductCodingService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ProductCodingServiceImpl extends CommonServiceImpl<ProductCodingMapper, ProductCoding> implements ProductCodingService {

    // private final RedisUtils redisUtils;
    private final ProductCodingMapper productCodingMapper;

    @Override
    public PageInfo<ProductCodingDto> queryAll(ProductCodingQueryParam query, Pageable pageable) {
        IPage<ProductCoding> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<ProductCoding> page = productCodingMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, ProductCodingDto.class);
    }

    @Override
    public List<ProductCodingDto> queryAll(ProductCodingQueryParam query){
        return ConvertUtil.convertList(productCodingMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), ProductCodingDto.class);
    }

    @Override
    public ProductCoding getById(Integer id) {
        return productCodingMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public ProductCodingDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), ProductCodingDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ProductCodingDto resources) {
        ProductCoding entity = ConvertUtil.convert(resources, ProductCoding.class);
        checkValidation(entity);
        return productCodingMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(ProductCodingDto resources){
        ProductCoding entity = ConvertUtil.convert(resources, ProductCoding.class);
        checkValidation(entity);
        int ret = productCodingMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    /**
     * 校验有效性：
     * 1. 编号&版本 做唯一性判断
     * 2. 产品号&是否禁用 做单产品唯一性判断
     * @param entity ProductCoding
     */
    private void checkValidation(ProductCoding entity) {
        if (DictValueEnum.START.getValue().equals(entity.getIsDisable())) {
            ProductCodingQueryParam param = new ProductCodingQueryParam();
            param.setIsDisable(entity.getIsDisable());
            param.setProductCode(entity.getProductCode());
            List<ProductCoding> codings = productCodingMapper.selectList(QueryHelpMybatisPlus.getPredicate(param));
            if (codings != null && !codings.isEmpty()) {
                if (entity.getId() == null) {
                    throw new EntityExistException(ProductCoding.class, "产品编号", entity.getProductCode());
                } else {
                    for (ProductCoding coding : codings) {
                        if (!entity.getId().equals(coding.getId())) {
                            throw new EntityExistException(ProductCoding.class, "产品编号", entity.getProductCode());
                        }
                    }
                }
            }
        }
        ProductCodingQueryParam param = new ProductCodingQueryParam();
        param.setCodingCode(entity.getCodingCode());
        param.setVersion(entity.getVersion());
        List<ProductCoding> codings = productCodingMapper.selectList(QueryHelpMybatisPlus.getPredicate(param));
        if (codings != null && !codings.isEmpty()) {
            if (entity.getId() == null) {
                throw new EntityExistException(ProductCoding.class, "规则编码 & 版本", entity.getCodingCode() + " & "
                        + entity.getVersion());
            } else {
                for (ProductCoding coding : codings) {
                    if (!entity.getId().equals(coding.getId())) {
                        throw new EntityExistException(ProductCoding.class, "规则编码 & 版本", entity.getCodingCode() + " & "
                                + entity.getVersion());
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids){
        // delCaches(ids);
        return productCodingMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id){
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<ProductCodingDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (ProductCodingDto productCoding : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("产品编码", productCoding.getProductCode());
              map.put("编码规则编码", productCoding.getCodingCode());
              map.put("编码规则名称", productCoding.getCodingName());
              map.put("类型", productCoding.getCodingType());
              map.put("编码生成示例", productCoding.getCodingExample());
              map.put("是否禁用", productCoding.getIsDisable());
              map.put("版本", productCoding.getVersion());
              map.put("描述", productCoding.getRemark());
              map.put("创建人", productCoding.getCreateBy());
              map.put("创建时间", productCoding.getCreateTime());
              map.put("更新人", productCoding.getUpdateBy());
              map.put("更新时间", productCoding.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
